package cn.tedu.controller;

import java.math.BigInteger;
import java.security.MessageDigest;
public class MD5Demo {
    private static final String SALT = "$2405JSD";
    // 生成加盐的MD5哈希
    public static String genMd5(String pwd) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest((pwd + SALT).getBytes());
            // 转换为十六进制数
            BigInteger number = new BigInteger(1, messageDigest);
            StringBuilder hexString = new StringBuilder(number.toString(16));
            while (hexString.length() < 32) {
                hexString.insert(0, '0');
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 检查密码是否与存储的加密版本匹配
    public static boolean check(String pwd, String sigPwd) {
        try {
// 重新生成输入密码的MD5哈希值
            String generatedPwd = genMd5(pwd);
// 比较生成的哈希与传入的哈希是否相同
            return generatedPwd.equals(sigPwd);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        String originalPwd = "123456";
        String storedPwd = MD5Demo.genMd5(originalPwd);
        System.out.println("Stored Hash: " + storedPwd);
        // 模拟校验过程   登录的时候storedPwd从数据库查出来
        boolean isMatch = MD5Demo.check("123456", storedPwd);
        System.out.println("Password valid: " + isMatch);
    }
}

